package com.message.queue.rocket.orderly;

import com.message.queue.constant.RocketConstant;
import com.message.queue.rocket.consumer.ConsumerParent;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 顺序消息消费者
 * Created by 张波 on 2019/10/14.
 */
public class Consumer extends ConsumerParent {

    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(CONSUMER_GROUP);
        consumer.setNamesrvAddr(RocketConstant.NAME_SERVER);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.subscribe(ConsumerParent.TOPIC, "*");
        consumer.registerMessageListener(new OrderlyConsumerListener());
        consumer.start();
    }


    public static class OrderlyConsumerListener implements MessageListenerOrderly {

        @Override
        public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
            /*设置自动提交*/
            context.setAutoCommit(true);
            System.out.println("msgs size:" + msgs.size());
            for(MessageExt msg : msgs) {
                try{
                    //TODO 执行业务处理
                    System.out.println("msg:" + new String(msg.getBody()));
                } catch (Exception e) {
                    /*出现异常时*/
                    return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                }

            }
            return ConsumeOrderlyStatus.SUCCESS;
        }
    }

}
